import json
import requests
import os
import time
import logging
from logging.handlers import RotatingFileHandler

class DownSeed:
    def __init__(self):
        self.logger = logging.getLogger("AutoDown")
        self.logger.setLevel(logging.DEBUG)
        if not self.logger.hasHandlers():
            handler = RotatingFileHandler('./Autodown.log', maxBytes=10*1024*1024, backupCount=1)
            formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
            handler.setFormatter(formatter)
            self.logger.addHandler(handler)
        self.api_url = "https://api.m-team.io/api/torrent/genDlToken"
        self.headers = {
            "accept": "*/*",
            "content-type": "application/x-www-form-urlencoded; charset=UTF-8",
            "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/527.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/527.36",
            "x-api-key": "" #填写自己的api
        }
    
    def start(self):
        try:
            with open("BtList.txt", "r", encoding='utf-8') as file:
                datas = json.load(file)
        except Exception as e:
            print(f"无法加载BtList.txt: {e}")
            return

        # 复制字典的键
        seed_ids = list(datas['data'].keys())
        for seed_id in seed_ids:
            if seed_id in datas['data']:
                seed_name = datas['data'][seed_id]['name']
                self.down_seed(seed_id, seed_name)
                del datas['data'][seed_id]
                with open("BtList.txt", "w", encoding='utf-8') as file:
                    json.dump(datas, file, ensure_ascii=False, indent=4)
                time.sleep(70)
    
    def down_seed(self, seed_id, seed_name):
        retry_delay = [20] + [60] * 9  # 第一次20秒，之后每次60秒
        attempt = 0
        while True:
            self.logger.info(f"🔄 请求种子: ID={seed_id}, 名称={seed_name}, 尝试次数={attempt+1}")
            try:
                response = requests.post(self.api_url, headers=self.headers, data={"id": seed_id}, timeout=10)
                response.raise_for_status()
                json_data = response.json()
                
                if json_data.get("message") == "SUCCESS" and json_data.get("data"):
                    self.logger.info(f"✅ 获取种子成功: {json_data['data']}")
                    self.download_seed(json_data['data'], f'{seed_id}---{seed_name}.torrent')
                    break
                else:
                    self.logger.warning(f"⚠️ 获取种子失败，服务器返回: {json_data}")
            except requests.RequestException as e:
                self.logger.error(f"❌ 请求错误: {e}")
            
            delay = retry_delay[min(attempt, len(retry_delay)-1)]
            self.logger.info(f"⏳ {delay}秒后重试...")
            time.sleep(delay)
            attempt += 1
    
    def download_seed(self, url, filename):
        import re
        filename = re.sub(r'[<>:"/\\|?*]', '-', filename)
        os.makedirs("./seed/", exist_ok=True)
        output_path = os.path.join("./seed/", filename)
        
        attempt = 0
        retry_delay = [20] + [60] * 9
        while True:
            self.logger.info(f"🔄 下载种子: {url}, 尝试次数={attempt+1}")
            try:
                response = requests.get(url, stream=True, timeout=10)
                response.raise_for_status()
                with open(output_path, 'wb') as f:
                    for chunk in response.iter_content(chunk_size=128*1024):
                        if chunk:
                            f.write(chunk)
                self.logger.info(f"✅ 种子文件已保存到：{output_path}")
                break
            except requests.RequestException as e:
                self.logger.error(f"❌ 下载失败: {e}")
            
            delay = retry_delay[min(attempt, len(retry_delay)-1)]
            self.logger.info(f"⏳ {delay}秒后重试...")
            time.sleep(delay)
            attempt += 1
    
if __name__ == "__main__":
    DownSeed().start()
